<?php

/**
 * Class AReply.php
 *
 * Class responsible for storing the responses of comments to the arguments at the stage of argument Discussion
 *
 * @author Jose Oliveira <jafo@ua.pt> 2012
 */

class AReply{

	private $reply;
	private $dateHour;
	private $aCommnetID;
	private $userID;

	/**
	 * 
	 * @param integer $reply
	 * @param integer $aCommentID
	 * @param integer $userID
	 */
	function __construct($reply, $aCommentID, $userID){

		if(isset($reply) && isset($aCommentID) && isset($userID)){
			$this->reply=$reply;
			$this->aCommnetID=$aCommentID;
			$this->userID=$userID;
			$this->dateHour=date("Y-m-d H:i:s");
		}

	}

	/**
	 *  Method that stores a new response to a certain comment
	 * @throws Exception
	 * @return bool
	 */
	public function storeReply(){

		if($this->reply != ""){
				
			$conn=new ConnDBUser();
			$conn->Connect();
				
			$result=mysql_query("insert into aReply(reply, dateHour, commentID, userID)
			values ('" . $this->reply . "', '" . $this->dateHour . "', '" . $this->aCommnetID . "', '" . $this->userID . "')");

			if(!$result){
				throw new Exception("Lamentamos mas ocorreu um erro ao guardar a sua resposta");
			}
				
			try{
				$conn->disconnect($result);
				return true;

			}catch(Exception $e){
				$e->getMessage();
			}
				
		}

	}

	/**
	 * Method that returns all replies made to a comment
	 * @param integer $commentID
	 * @throws Exception
	 * @return array
	 */
	public function getReplies($commentID){

		$conn=new ConnDBUser();
		$conn->connect();

		$result=mysql_query("select * from aReply where commentID='$commentID'");

		if(!$result){
			throw new Exception("Lamentamos mas ocorreu um erro");
		}

		try{

			$info=array();
			while($registo=mysql_fetch_array($result)){
					
				$name=$this->getUserName($registo['userID']);

				$temp=array('aReplyID' => $registo['replyID'], 'reply' => $registo['reply'], 'dateHour' => $registo['dateHour'],
				'commentID' => $registo['commentID'], 'author' => $name);

				array_push($info, $temp);
			}

			$conn->disconnect($result);
			return $info;

		}catch(Exception $e){
			$e->getMessage();
		}
	}
	
	/**
	 * Method that receives an userID and returns the respective username 
	 * @param integer $userID
	 * @throws Exception
	 * @return string
	 */
	private function getUserName($userID){

		$conn=new ConnDBUser();
		$conn->connect();

		$result=mysql_query("select name from user where userID='$userID'");

		if(!$result){
			throw new Exception("Lamentamos mas ocorreu um erro");
		}

		try{

			$registo=mysql_fetch_array($result);

			$conn->disconnect($result);
			return $registo['name'];

		}catch(Exception $e){
			print $e->getMessage();
		}

	}



}